/**
* @param {Object[]} searchList 
  * @param {string}  name - 表单绑定的key,
  * @param {string}  title - 标题,
  * @param {string}  type - 类型 (input,select,datepicker,...),
  * @param {Object}  otherProps - 其他属性
                          如：options - [{
                            label: '交通厅',
                            value: 1,
                          }],
*/

import React, { useImperativeHandle, forwardRef } from 'react';
import './index.less';
import { Button, Space, Form, Input, Select, DatePicker } from 'antd';
function SearchList({ searchList, initList, isLongTitle }, ref) {
  const [form] = Form.useForm();

  const reset = () => {
    form.resetFields();
    searchFn();
  };

  const searchFn = (values) => {
    initList && initList(values);
  };

  const componentsMap = (type) => {
    const typeList = {
      input: <Input></Input>,
      select: <Select></Select>,
      datepicker: <DatePicker></DatePicker>,
    };
    return typeList[type] || typeList.input;
  };
  const getValueProps = (item) => {
    const props = { ...item.otherProps };
    props.placeholder = item.type === 'input' ? '请输入' : '请选择';
    props.allowClear = true;
    return () => props;
  };
  const isMuti = searchList.length > 2;

  useImperativeHandle(ref, () => ({
    searchFn: (newVal) => {
      return form.getFieldsValue();
    },
  }));

  return (
    <div className={isMuti ? 'layout-muti bgf search-x' : 'bgf search-x'}>
      <Form
        form={form}
        layout="inline"
        onFinish={searchFn}
        className={isLongTitle ? 'isLongTitle' : ''}
      >
        {searchList.map((item) => {
          return (
            <Form.Item
              key={item.name}
              label={item.title}
              name={item.name}
              getValueProps={getValueProps(item)}
            >
              {componentsMap(item.type)}
            </Form.Item>
          );
        })}
        <Space className="btns-x" size={18}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button type="primary" onClick={reset} className="cancel-btn">
            重置
          </Button>
        </Space>
      </Form>
    </div>
  );
}

export default forwardRef(SearchList);
